import { Controller, UseGuards } from '@nestjs/common';
import { Crud, CrudAuth ,CrudController, Override, ParsedRequest, ParsedBody, CrudRequest } from '@nestjsx/crud';
import { ApiTags, ApiBearerAuth, ApiBody} from '@nestjs/swagger';
import { Cart } from '../../entities/cart.entities';
import { CartService } from '../../services/cart/cart.service';
import { AuthGuard } from '@nestjs/passport';
import { ProductService } from '../../services/product/product.service';

@Crud({
  model:{
    type:Cart,
  },
  query:{
    exclude:["order_id"]
  },
  routes:{
    only:['createOneBase','deleteOneBase','getManyBase']
  }
})
@CrudAuth({
  property:"user",
  filter: (user) => ({
    user_id: user.userId
  }),
  persist:(user) => {
    return user;
  }
})
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
@ApiTags('cart')
@Controller('api/cart')
export class CartController implements CrudController<Cart>{
  constructor(
    public service:CartService,
    private productService:ProductService
  ){}

  get base(): CrudController<Cart> {
    return this;
  }

  @ApiBody({
    type: Cart
  })
  @Override()
  async createOne(
    @ParsedRequest() req: CrudRequest,
    @ParsedBody() dto: Cart): Promise<Cart> {
    dto.user_id=req.parsed.authPersist.userId;
    const product=await this.productService.repo.findOne({
      where:{
        id:dto.product_id
      },
      relations:['goods']
    });
    dto.goods_id=product.goods_id;
    dto.list_pic_url=product.goods.list_pic_url;
    dto.goods_name=product.goods.name;
    dto.goods_sn=product.goods_sn;
    dto.product_id=product.id;
    dto.market_price=product.goods.market_price;
    dto.retail_price=product.retail_price;
    return this.base.createOneBase(req, dto);
  }

  @ApiBody({
    type: Cart
  })
  @Override()
  updateOne(
    @ParsedRequest() req: CrudRequest,
    @ParsedBody() dto: any): Promise<Cart> {
    dto.user_id=req.parsed.authPersist.userId
    return this.base.updateOneBase(req, dto);
  }
}
